package com.example.calculatorApp.service.impl;


import com.example.calculatorApp.common.Result;
import com.example.calculatorApp.controller.dto.LoginDTO;
import com.example.calculatorApp.controller.request.LoginRequest;
import com.example.calculatorApp.entity.Admin;
import com.example.calculatorApp.exception.ServiceException;
import com.example.calculatorApp.mapper.AdminMapper;
import com.example.calculatorApp.service.IAdminService;
import com.example.calculatorApp.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class adminServiceIMP implements IAdminService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public Object login(LoginRequest loginRequest) {
        Admin admin = adminMapper.login(loginRequest);
        if(admin==null){
            throw new ServiceException("用戶名或密碼錯誤");
        }
        if(admin.getStatus()!=1){
            throw new ServiceException("當前用戶已被禁用,請聯系管理員");
        }
        LoginDTO loginDTO = new LoginDTO();
        BeanUtils.copyProperties(admin,loginDTO);

        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassWord());
        loginDTO.setToken(token);

       return  Result.success(loginDTO);

    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }
}
